package com.yipin.neimeng.scheduler;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yipin.neimeng.constant.ErrorConstant;
import com.yipin.neimeng.dbpojo.NeimengCmccOrders;
import com.yipin.neimeng.service.NeimengCmccOrdersService;
import com.yipin.neimeng.util.HttpJsonInvokeDemo;
import com.yipin.neimeng.util.Md5Util;
import com.yipin.neimeng.util.OkHttpUtils;
import com.yipin.neimeng.vo.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class TimedTaskOrder {

    @Autowired
    NeimengCmccOrdersService neimengCmccOrdersService;

    private static final String SEND_MSG_URL = "http://36.189.241.29:81/oppf";
    private static final String APP_KEY = "b49644385f34023eb9ab929fcbe79bb3";

    private static final String OWNKEY = "0duyxk7rocwabeoo9fbpgujk659cubo8";

    private static final String AppId = "502739";   //应用AppId\

    private static final String YS_CALLBACK_URL = "http://101.200.36.40:8111/ypys/v1/callback";

    Logger logger = LoggerFactory.getLogger(TimedTaskOrder.class);
    /**
     * 5分钟执行
     */
    @Scheduled(fixedRate = 1000 * 60 * 5)
    public void selcteOrder() {
        String result;

        QueryWrapper<NeimengCmccOrders> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(NeimengCmccOrders::getStatus, 2);

        List<NeimengCmccOrders> list = neimengCmccOrdersService.list(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        log.info("查询到的订单："+list);


        try {
            for (NeimengCmccOrders neimengCmccOrders : list) {

                String appId = AppId;   // 应用AppId
                String opCode = "SYS71015406";
                String opOrgId = "71012628";
                String channelId = "9137";
                String linkUrl = neimengCmccOrders.getThirdContact();
                String AppName = neimengCmccOrders.getSecContact();

                if (linkUrl == null || "".equals(linkUrl)) {
                    linkUrl="其他";
                }
                if (AppName == null || "".equals(AppName)) {
                    AppName="其他";
                }

            JSONObject QreqJson = new JSONObject();
            JSONObject QpubJson = new JSONObject();
            JSONObject QpageJson = new JSONObject();
            JSONObject QbusiJson = new JSONObject(); // 创建业务信息的JSONObject

// PUB_INFO 参数
            QpubJson.put("OP_CODE", "SYS71015406");
            QpubJson.put("REQ_SERIAL_NO", neimengCmccOrders.getOrderNumber());
            QpubJson.put("CHANNEL_ID", "9137");
            QpubJson.put("OP_ORG_ID", "71012628");

// PAGE_INFO 参数
            QpageJson.put("PAGE_SIZE", "2");
            QpageJson.put("CURRENT_PAGE", "1");

            String orderId =generateOrderId();
// BUSI_INFO 参数
            QbusiJson.put("ORDER_ID", orderId);
            QbusiJson.put("REMARKS", "dasdasd");
            QbusiJson.put("ACCESS_NUM", neimengCmccOrders.getPhone());
            QbusiJson.put("LINK_URL", linkUrl);
            QbusiJson.put("APPLY_BROWSE_APP_NAME", AppName);
            QbusiJson.put("ORDER_BUSINESS_NAME", neimengCmccOrders.getProductName());
            QbusiJson.put("ORDER_BUSINESS_CODE", neimengCmccOrders.getProductCode());
            QbusiJson.put("APPLY_IP", neimengCmccOrders.getIp());
            QbusiJson.put("BUSINESS_APPLY_TIME", neimengCmccOrders.getCreateDateTime());

// 将PUB_INFO, PAGE_INFO, 和 BUSI_INFO放入REQ_PARAM
            QreqJson.put("PUB_INFO", QpubJson);
            QreqJson.put("PAGE_INFO", QpageJson);
            QreqJson.put("BUSI_INFO", QbusiJson); // 注意这里使用QbusiJson而不是busiJson

// 创建最终的REQ_PARAM JSONObject
            JSONObject QinputJson = new JSONObject();
            QinputJson.put("REQ_PARAM", QreqJson);

// 将整个JSON转换为字符串
            String IbusiParam = QinputJson.toString();

            log.info("回传请求入参："+IbusiParam);
            String methods = "CRM_ORD_SAVE_CEC_ORDERINFO_001";

            String headerString="http://111.56.125.2:21017/oppf?method="+methods+
                    "&appId="+appId+
                    "&OP_CODE="+opCode+
                    "&OP_ORG_ID="+opOrgId+
                    "&CHANNEL_ID="+channelId+
                    "&timestamp="+new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar
                    .getInstance().getTime());
            log.info("回传请求地址："+headerString);

           String find = HttpJsonInvokeDemo.encryptMessage(IbusiParam,"1",APP_KEY,"AES");

            log.info("回传加密后的参数："+find);

            try(HttpResponse response = HttpUtil.createPost(headerString)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(find)
                    .execute()){
                result = response.body();
            }catch (Exception e) {
                throw new RuntimeException("HTTP 请求失败", e);
            }

            log.info("响应结果(未解密)："+result);

            String selectorder = HttpJsonInvokeDemo.decryptMessage(result, "1", APP_KEY,"AES");

            log.info("解密后的响应结果："+selectorder);
            neimengCmccOrders.setReuqestSelect(selectorder);

            // 这里可以处理重试失败的情况，比如返回错误信息
            JSONObject resultJson = JSON.parseObject(selectorder);

            String findcode = resultJson.getJSONObject("RSP_PARAM")
                    .getJSONObject("BUSI_INFO")
                    .getString("CHECK_FLAG");

                Integer cont = neimengCmccOrders.getSelectCont();

                log.info("查询次数："+cont);
            if ("2044".equals(findcode)){

                cont++;
                neimengCmccOrders.setSelectCont(cont);
                neimengCmccOrders.setStatus("1");
                neimengCmccOrdersService.updateById(neimengCmccOrders);
                log.info("回调云枢.....");
                callBackYunShu(neimengCmccOrders,0,"订购成功");
            }else if("2043".equals(findcode)){
                cont++;
                if (cont ==3){
                    neimengCmccOrders.setStatus("0");
                    neimengCmccOrders.setSelectCont(cont);
                    log.info("查询次数："+cont);
                    neimengCmccOrdersService.updateById(neimengCmccOrders);
                    callBackYunShu(neimengCmccOrders,1,"订购失败");
                    log.info("回调云枢......");
                }
                neimengCmccOrders.setSelectCont(cont);
                neimengCmccOrdersService.updateById(neimengCmccOrders);
                log.info("订购失败正在重试。");

            }
        }

        }catch (Exception e){
            log.info("异常信息："+e.getMessage());
        }

    }

    public void callBackYunShu(NeimengCmccOrders neimengCmccOrders, Integer status,String message) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        Map<String, Object> YSparams = new HashMap<>();
        YSparams.put("channelCode", neimengCmccOrders.getChannelCode());
        YSparams.put("outoOrderNo", neimengCmccOrders.getOutoOrderNo());
        YSparams.put("orderNo", neimengCmccOrders.getOrderNo());
        YSparams.put("status", status);
        YSparams.put("ownsign", Md5Util.encryptMD5(timestamp + OWNKEY));
        YSparams.put("timestamp", timestamp);
        YSparams.put("msg", message);
        String json = JSON.toJSONString(YSparams);
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String result;
        logger.info("回调云枢入参:{}", json);
        result = OkHttpUtils.postRequest(YS_CALLBACK_URL, headers, YSparams);
        logger.info("回调云枢结果:{}", result);
        if (result == null) {
            logger.info("回调云枢失败:{}", neimengCmccOrders.getPhone());
            return;
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if ("0000".equals(jsonObject.getString("code"))) {
            logger.info("回调云枢成功:{}", neimengCmccOrders.getPhone());
        } else {
            logger.info("回调云枢失败:{}", neimengCmccOrders.getPhone());
        }
    }

    private static String generateOrderId() {
        // 获取当前时间的时间戳
        long timestamp = System.currentTimeMillis();

        // 生成一个随机数
        Random random = new Random();
        int randomNumber = random.nextInt(900000) + 100000; // 生成一个6位的随机数

        // 将时间戳和随机数拼接成一个字符串
        String orderId = String.valueOf(timestamp) + randomNumber;

        // 确保总长度为15位
        if (orderId.length() > 15) {
            orderId = orderId.substring(0, 15);
        } else if (orderId.length() < 15) {
            // 如果不足15位，补充随机数
            while (orderId.length() < 15) {
                orderId += random.nextInt(10);
            }
        }

        return orderId;
    }

}
